package cn.steam.foo.util.lock;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author zhang jintao on 2022/05/19
 **/
@Service
@Slf4j
public class RedissonLock implements Lock {

    private static final ThreadLocal<RLock> LOCK_THREAD_LOCAL = new InheritableThreadLocal<>();

    @Autowired
    RedissonClient redissonClient;

    @Override
    public boolean tryLock(String key) {
        RLock lock = redissonClient.getLock(key);
        if (lock.tryLock()) {
            log.info("设置分布式锁成功,key:{}", key);
            LOCK_THREAD_LOCAL.set(lock);
            return true;
        }
        return false;
    }

    @Override
    public boolean lock(String key) {
        return this.tryLock(key);
    }

    @Override
    public boolean lock(String key, int timeout, TimeUnit timeUnit) {
        return this.tryLock(key);
    }

    @Override
    public void unlock(String key) {
        RLock lock = LOCK_THREAD_LOCAL.get();
        lock.unlock();
        LOCK_THREAD_LOCAL.remove();
        log.info("释放分布式锁成功,key:{}", key);
    }
}
